package com.sanq.product.books.controller;

import com.sanq.product.books.entity.vo.OrdersVo;
import com.sanq.product.books.service.OrdersService;
import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.entity.Pager;
import com.sanq.product.config.utils.entity.Pagination;
import com.sanq.product.config.utils.entity.Response;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/orders")
public class OrdersController {

    @Resource
    private OrdersService ordersService;

    @LogAnnotation(description = "通过ID得到详情")
    @GetMapping(value = "/get/{id}")
    public Response getById(HttpServletRequest request, @PathVariable("id") Integer id) {
        OrdersVo ordersVo = ordersService.findById(id);

        return ordersVo != null ? new Response().success(ordersVo) : new Response().failure();
    }

    @LogAnnotation(description = "删除数据")
    @DeleteMapping(value = "/delete")
    public Response deleteById(HttpServletRequest request, @RequestBody OrdersVo ordersVo) {

        int result = ordersService.delete(ordersVo);
        return result == 1 ? new Response().success() : new Response().failure();
    }

    @LogAnnotation(description = "分页查询数据")
    @GetMapping(value = "/list")
    public Response findListByPager(HttpServletRequest request,
                                    OrdersVo ordersVo,
                                    Pagination pagination,
                                    @RequestParam(value = "dateTimeRange[]", required = false) String[] dateTimeRange) {


        ordersVo.setTimes(dateTimeRange);

        Pager<OrdersVo> pager = ordersService.findListByPage(ordersVo, pagination);

        return pager != null ? new Response().success(pager) : new Response().failure();
    }

    @LogAnnotation(description = "查询所有数据")
    @GetMapping(value = "/all")
    public Response findList(HttpServletRequest request, OrdersVo ordersVo) {

        List<OrdersVo> list = ordersService.findList(ordersVo);
        return list != null ? new Response().success(list) : new Response().failure();
    }

    @LogAnnotation(description = "添加数据")
    @PostMapping(value = "/save")
    public Response add(HttpServletRequest request, @RequestBody OrdersVo ordersVo) {

        int result = ordersService.save(ordersVo);

        return result == 1 ? new Response().success() : new Response().failure();
    }

    @LogAnnotation(description = "通过ID修改数据")
    @PutMapping(value = "/update/{id}")
    public Response updateByKey(HttpServletRequest request,
                                @RequestBody OrdersVo ordersVo,
                                @PathVariable("id") Integer id) {

        int result = ordersService.update(ordersVo, id);

        return result == 1 ? new Response().success() : new Response().failure();
    }
}
